/**
 * WeChatToken.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/#!documentation/models
 */

/**
 * 微信 Js-SDK Token
 * @type {{attributes: {appid: {type: string, required: boolean}, secret: {type: string, required: boolean}, access_token: {type: string, required: boolean}, token_timestamp: {type: string, required: boolean}, jsapi_ticket: {type: string, required: boolean}, ticket_timestamp: {type: string, required: boolean}, ip_list: {type: string}}, findData: Function, saveData: Function}}
 */
module.exports = {
  //connection: "memory",
  attributes: {
    // AppId 在微信公众平台后台查看
    "appid": {
      type: "string",
      required: true
    },
    // Secret 在微信公众平台后台查看
    "secret": {
      type: "string",
      required: true
    },
    // access token, 基础接口获取
    "access_token": {
      type: "string",
      required: true
    },
    // 生成access token的时间, ms级别, 此时间 + 7000,000 与当前时间比较是否过期
    "token_timestamp": {
      type: "integer",
      required: true
    },
    // jsapi ticket 基础接口获取
    "jsapi_ticket": {
      type: "string",
      required: true
    },
    // 生成jsapi ticket的时间, ms级别, 此时间 + 7000,000 与当前时间比较是否过期
    "ticket_timestamp": {
      type: "integer",
      required: true
    },
    // 微信服务器ip地址列表
    "ip_list": {
      "type": "array"
    }
  },
  findData: function (appid, cb) {
    this.find({"appid": appid}).limit(1).exec(cb);
  },
  saveData: function (appid, updata, cb) {
    var self = this;

    self.find({"appid": appid}, function (err, data) {
      if (err) {
        return cb(err);
      }
      if (!data || data.length == 0) {
        // no record create
        self.create(updata, cb);
      } else {
        // update
        self.update({"appid": appid}, updata, cb);
      }
    });
  }
};

